<template>
  <div id="profile">
    <div class="container">
      <!-- 左侧导航 -->
      <aside class="sidebar">
        <div class="user-info">
          <img :src="user.avatar" alt="头像" class="avatar" />
          <h3>{{ user.name }}</h3>
        </div>

        <nav>
          <ul>
            <li
              @click="selectTab('profile')"
              :class="{ active: activeTab === 'profile' }"
            >
              👤 个人中心
            </li>
            <li
              @click="selectTab('courses')"
              :class="{ active: activeTab === 'courses' }"
            >
              📚 课程管理
            </li>
            <li
              @click="selectTab('canvas')"
              :class="{ active: activeTab === 'canvas' }"
            >
              🎨 用户画布
            </li>
            <li
              @click="selectTab('favorites')"
              :class="{ active: activeTab === 'favorites' }"
            >
              ⭐ 历史收藏
            </li>
            <li
              @click="selectTab('history')"
              :class="{ active: activeTab === 'history' }"
            >
              📜 浏览记录
            </li>
            <li
              @click="selectTab('stats')"
              :class="{ active: activeTab === 'stats' }"
            >
              📊 数据统计
            </li>
          </ul>
        </nav>

        <!-- 回到主页按钮 -->
        <button class="home-btn" @click="goHome">🏠 回到主页</button>
      </aside>

      <!-- 右侧内容区域 -->
      <main class="content">
        <div v-if="activeTab === 'profile'">
          <h2>个人中心</h2>

          <el-form ref="profileForm" :model="user" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username" placeholder="请输入用户名" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" placeholder="请输入邮箱" />
            </el-form-item>

            <el-form-item label="电话" prop="phone">
              <el-input v-model="user.phone" placeholder="请输入电话号码" />
            </el-form-item>

            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="user.birthday"
                type="date"
                placeholder="选择生日"
              />
            </el-form-item>

            <el-form-item label="性别" prop="sex">
              <el-select v-model="user.sex" placeholder="选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="简介">
              <el-input
                v-model="user.bio"
                type="textarea"
                placeholder="填写个人简介"
              />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="user.address" placeholder="请输入地址" />
            </el-form-item>

            <el-form-item label="职位" prop="job_title">
              <el-input v-model="user.jobTitle" placeholder="请输入职位" />
            </el-form-item>

            <el-form-item label="行业" prop="industry">
              <el-input v-model="user.industry" placeholder="请输入行业" />
            </el-form-item>

            <el-form-item label="QQ" prop="qq">
              <el-input v-model="user.qq" placeholder="请输入QQ号" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm">保存修改</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div v-if="activeTab === 'courses'">
          <h2>课程管理</h2>
          <MyCourse />
        </div>

        <div v-if="activeTab === 'canvas'" class="canvas-container">
          <h2>用户画布</h2>
          <el-input
            v-model="jsonString"
            type="textarea"
            :rows="35"
            readonly
            resize="none"
            class="json-textarea"
          />

          <el-button
            type="primary"
            icon="el-icon-document-copy"
            @click="copyToClipboard"
          >
            复制 JSON
          </el-button>
        </div>

        <div v-if="activeTab === 'favorites'">
          <h2>历史收藏</h2>

          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="coverImage" label="封面" width="120">
              <template #default="{ row }">
                <el-image
                  style="width: 100px; height: 60px"
                  :src="row.coverImage"
                  fit="cover"
                />
              </template>
            </el-table-column>

            <el-table-column
              prop="title"
              label="标题"
              width="200"
              show-overflow-tooltip
            />

            <el-table-column prop="tags" label="标签" width="120" />

            <el-table-column
              prop="collectCount"
              label="收藏数"
              width="100"
              align="center"
            />

            <el-table-column
              prop="downloadCount"
              label="下载数"
              width="100"
              align="center"
            />

            <el-table-column
              prop="shareCount"
              label="分享数"
              width="100"
              align="center"
            />

            <el-table-column
              prop="rating"
              label="评分"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <el-rate
                  v-model="row.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createTime) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(row.id)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-if="activeTab === 'history'">
          <h2>浏览记录</h2>
          <el-table :data="tableDataView" border style="width: 100%">
            <el-table-column prop="coverImage" label="封面" width="120">
              <template #default="{ row }">
                <el-image
                  style="width: 100px; height: 60px"
                  :src="row.coverImage"
                  fit="cover"
                />
              </template>
            </el-table-column>

            <el-table-column
              prop="title"
              label="标题"
              width="200"
              show-overflow-tooltip
            />

            <el-table-column prop="tags" label="标签" width="120" />

            <el-table-column
              prop="collectCount"
              label="收藏数"
              width="100"
              align="center"
            />

            <el-table-column
              prop="downloadCount"
              label="下载数"
              width="100"
              align="center"
            />

            <el-table-column
              prop="shareCount"
              label="分享数"
              width="100"
              align="center"
            />

            <el-table-column
              prop="rating"
              label="评分"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <el-rate
                  v-model="row.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.createTime) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteHistory(row.id)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div v-if="activeTab === 'stats'">
          <h2>数据统计</h2>
          <div class="stats-container">
            <!-- 完成的课程统计 -->
            <div class="chart-box">
              <h3>🎓 完成的课程</h3>
              <div ref="courseChart" class="chart"></div>
            </div>

            <!-- 词云（学习标签统计） -->
            <div class="chart-box">
              <h3>🏷️ 学习标签统计</h3>
              <div ref="wordCloudChart" class="chart"></div>
            </div>

            <!-- 柱状图：学习习惯统计 -->
            <div class="chart-box">
              <h3>📅 学习习惯统计</h3>
              <div ref="habitChart" class="chart"></div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>
  
  <script>
import MyCourse from "../myUploadCourseViews/index.vue";
import * as echarts from "echarts";
import "echarts-wordcloud"; // 引入词云插件
export default {
  name: "Profile",
  components: {
    MyCourse,
  },
  data() {
    return {
      user: {
        username: "",
        email: "",
        phone: "",
        birthday: "",
        sex: "",
        bio: "",
        avatar: "",
        address: "",
        jobTitle: "",
        industry: "",
        qq: "",
        status: "1", // 默认值
      },
      tableData: [
        {
          coverImage: "",
          title: "",
          category: "",
          collectCount: "",
          downloadCount: "",
          shareCount: "",
          rating: "",
          createTime: "",
          tags: "",
        },
      ],
      tableDataView: [
        {
          coverImage: "",
          title: "",
          category: "",
          collectCount: "",
          downloadCount: "",
          shareCount: "",
          rating: "",
          createTime: "",
          tags: "",
        },
      ],
      activeTab: "profile",
      courses: [],
      favorites: [],
      history: [],
      activeTab: "canvas",
      jsonData: {},
    };
  },
  computed: {
    jsonString() {
      return JSON.stringify(this.jsonData, null, 2); // 格式化 JSON
    },
  },
  mounted() {
    // 模拟获取数据
    this.courses = [
      { id: 1, name: "Java 基础" },
      { id: 2, name: "Spring Boot 实战" },
    ];
    this.favorites = [
      { id: 1, title: "设计模式" },
      { id: 2, title: "数据结构" },
    ];
    this.history = [
      { id: 1, page: "Vue 3 响应式" },
      { id: 2, page: "MySQL 优化" },
    ];
  },
  methods: {
    selectTab(tab) {
      this.activeTab = tab;
      if (tab === "stats") {
        this.initCourseChart();
        this.initWordCloudChart();
        this.initHabitChart();
      }
    },
    updateProfile() {
      console.log("修改用户信息：", this.user);
      alert("信息已更新");
    },
    goHome() {
      this.$router.push("/index");
    },

    //   获取用户个人信息
    getProfile() {
      let url = "/api/sysUser/detail";
      this.$http.get(url).then((res) => {
        this.user = res.data.data;
        // 将用户头像加上http://localhost:8585/uploads/
        this.user.avatar =
          "http://localhost:8585/uploads/" + res.data.data.avatar;
        console.log(res.data.data);
      });
    },
    submitForm() {},
    resetForm() {
      this.$refs.profileForm.resetFields();
    },
    // 获取全部历史收藏
    getAllProduct() {
      let url = "/api/resources/collect/list";
      this.$http.get(url).then((res) => {
        this.tableData = res.data.data;
      });
    },
    formatDate(dateStr) {
      return new Date(dateStr).toLocaleString();
    },
    handleEdit(row) {
      console.log("编辑", row);
    },
    handleDelete(id) {
          // 移除历史记录

      //  提示删除信息
      this.$confirm("是否删除该历史记录", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 确认删除
          let url = "/api/resources/collect/delete/" + id;
          this.$http.delete(url).then((res) => {
            if (res.data.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getAllProduct();
            } else {
              this.$message({
                type: "error",
                message: "删除失败",
              });
            }
          });
        })
        .catch(() => {
          // 取消删除
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    
    },

    // 获取浏览历史记录
    getAllView() {
      let url = "/api/resources/views/list";
      this.$http.get(url).then((res) => {
        this.tableDataView = res.data.data;
        // console.log(res.data.data);
      });
    },
    copyToClipboard() {
      navigator.clipboard
        .writeText(this.jsonString)
        .then(() => {
          this.$message.success("JSON 复制成功！");
        })
        .catch(() => {
          this.$message.error("复制失败，请重试！");
        });
    },

    // 获取用户画布
    getCanvas() {
      let url = "/api/resources/userProfile";
      this.$http.get(url).then((res) => {
        this.jsonData = res.data.data;
        console.log(res.data.data);
      });
    },

    // 完成的课程（饼图）
    initCourseChart() {
      this.$nextTick(() => {
        if (!this.$refs.courseChart) {
          console.error("DOM 未找到");
          return;
        }

        let chart = echarts.init(this.$refs.courseChart);
        chart.setOption({
          title: {
            text: "已完成课程统计",
            left: "center",
            textStyle: { fontSize: 16, fontWeight: "bold" },
          },
          tooltip: {
            trigger: "item",
            formatter: "{b}: {c} ({d}%)",
          },
          legend: {
            orient: "vertical",
            left: "left",
          },
          series: [
            {
              name: "课程类别",
              type: "pie",
              radius: ["40%", "65%"], // 设置环形饼图
              roseType: "radius", // 让数据大小决定扇形半径
              label: {
                show: true,
                formatter: "{b}: {c} ({d}%)",
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
              data: [
                { value: 22, name: "Java" },
                { value: 18, name: "Python" },
                { value: 15, name: "Vue.js" },
                { value: 12, name: "数据库" },
                { value: 10, name: "机器学习" },
                { value: 8, name: "Spring Boot" },
                { value: 6, name: "数据结构" },
                { value: 5, name: "操作系统" },
              ],
              color: [
                "#5470C6",
                "#91CC75",
                "#FAC858",
                "#EE6666",
                "#73C0DE",
                "#3BA272",
                "#FC8452",
                "#9A60B4",
              ], // 自定义配色
            },
          ],
        });
      });
    },

    initWordCloudChart() {
      this.$nextTick(() => {
        if (!this.$refs.wordCloudChart) {
          console.error("DOM 未找到");
          return;
        }

        let chart = echarts.init(this.$refs.wordCloudChart);
        let wordData = [
          { name: "Java", value: 200 },
          { name: "Python", value: 180 },
          { name: "Vue.js", value: 160 },
          { name: "算法", value: 140 },
          { name: "数据库", value: 130 },
          { name: "机器学习", value: 120 },
          { name: "LeetCode", value: 110 },
          { name: "Spring Boot", value: 100 },
          { name: "数据结构", value: 90 },
          { name: "操作系统", value: 85 },
          { name: "Linux", value: 80 },
          { name: "C++", value: 75 },
          { name: "Redis", value: 70 },
          { name: "Nginx", value: 65 },
          { name: "Docker", value: 60 },
          { name: "Kubernetes", value: 55 },
          { name: "深度学习", value: 50 },
          { name: "前端", value: 45 },
          { name: "后端", value: 40 },
          { name: "架构", value: 35 },
          { name: "大数据", value: 30 },
          { name: "微服务", value: 25 },
        ];

        // **随机生成颜色，确保每个单词都不同**
        function getRandomColor(index, value) {
          let hue = Math.floor(Math.random() * 360); // 随机色相 (0°~360°)
          let saturation = 70 + (value / 200) * 20; // 随机饱和度 (70%~90%)
          let lightness = 40 + (value / 200) * 30; // 词越大颜色越亮 (40%~70%)
          return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
        }

        // 生成新的数据，绑定颜色
        let wordDataWithColors = wordData.map((item, index) => ({
          ...item,
          itemStyle: { color: getRandomColor(index, item.value) },
        }));

        chart.setOption({
          series: [
            {
              type: "wordCloud",
              shape: "circle",
              sizeRange: [14, 60],
              rotationRange: [-45, 45],
              gridSize: 6,
              drawOutOfBound: false,
              textStyle: {
                fontFamily: "Arial",
                fontWeight: "bold",
              },
              data: wordDataWithColors, // 绑定带颜色的数据
            },
          ],
        });
      });
    },

    // 学习习惯（柱状图）

    initHabitChart() {
      this.$nextTick(() => {
        if (!this.$refs.habitChart) {
          console.error("DOM 未找到");
          return;
        }

        let chart = echarts.init(this.$refs.habitChart);
        chart.setOption({
          grid: { left: "10%", right: "10%", bottom: "10%" }, // 调整布局
          tooltip: {
            trigger: "axis",
            axisPointer: { type: "shadow" },
          },
          xAxis: {
            type: "category",
            data: ["早晨", "上午", "下午", "晚上"],
            axisTick: { alignWithLabel: true },
            axisLine: { lineStyle: { color: "#888" } }, // 坐标轴颜色
          },
          yAxis: {
            type: "value",
            splitLine: { show: false }, // 不显示背景网格线
            axisLine: { lineStyle: { color: "#888" } },
          },
          series: [
            {
              name: "学习时间（小时）",
              type: "bar",
              data: [2, 4, 3, 5],
              barWidth: "40%", // 柱子的宽度
              itemStyle: {
                borderRadius: [5, 5, 0, 0], // 圆角柱子
                color: function (params) {
                  // 渐变色方案
                  let colorList = [
                    ["#5470C6", "#91CC75"],
                    ["#FAC858", "#EE6666"],
                    ["#73C0DE", "#3BA272"],
                    ["#FC8452", "#9A60B4"],
                  ];
                  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: colorList[params.dataIndex][0] },
                    { offset: 1, color: colorList[params.dataIndex][1] },
                  ]);
                },
              },
              label: {
                show: true,
                position: "top",
                color: "#333",
                fontSize: 14,
                fontWeight: "bold",
              },
            },
          ],
        });
      });
    },

    // 移除历史记录
    deleteHistory(id) {
      //  提示删除信息
      this.$confirm("是否删除该历史记录", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 确认删除
          let url = "/api/resources/views/delete/" + id;
          this.$http.delete(url).then((res) => {
            if (res.data.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.getAllProduct();
            } else {
              this.$message({
                type: "error",
                message: "删除失败",
              });
            }
          });
        })
        .catch(() => {
          // 取消删除
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  mounted() {
    this.getProfile();
    this.getAllProduct();
    this.getCanvas();
    this.getAllView();
  },
};
</script>
  
  <style scoped lang="less">
/* 页面整体布局 */
.container {
  display: flex;
}

/* 左侧导航 */
.sidebar {
  width: 250px;
  background: #2c3e50;
  color: white;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-info {
  text-align: center;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 10px;
  border: 2px solid #fff;
}

.sidebar nav ul {
  list-style: none;
  padding: 0;
}

.sidebar nav ul li {
  padding: 10px;
  cursor: pointer;
  text-align: center;
  border-radius: 5px;
  transition: 0.3s;
}

.sidebar nav ul li:hover,
.sidebar nav ul li.active {
  background: #34495e;
}

/* 右侧内容区域 */
.content {
  flex: 1;
  padding: 20px;
}

/* 表单样式 */
form {
  max-width: 400px;
}

label {
  display: block;
  margin-top: 10px;
}

input {
  width: 100%;
  padding: 5px;
  margin-top: 5px;
}

button {
  margin-top: 10px;
  padding: 8px 12px;
  background: #2c3e50;
  color: white;
  border: none;
  cursor: pointer;
}

button:hover {
  background: #34495e;
}

/* 回到主页按钮 */
.home-btn {
  width: 100%;
  padding: 10px;
  background: #e74c3c;
  color: white;
  border: none;
  cursor: pointer;
  margin-top: 20px;
  border-radius: 5px;
  font-size: 16px;
  transition: 0.3s;
}

.home-btn:hover {
  background: #c0392b;
}
.stats-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.chart-box {
  width: 80%;
  min-height: 350px;
  background: #fff;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.chart {
  width: 100%;
  height: 300px;
}
/deep/ .header {
  display: none;
}
/deep/ .title {
  display: none;
}
/deep/ .main {
  width: 100%;
  margin: auto;
}
</style>
  